<template>
  <view class="climber-orders">
    <!-- 头部标题 -->
    <view class="header">
      <text class="title">陪跑员接单</text>
    </view>

    <!-- 筛选标签 -->
    <view class="filter-tabs">
      <text 
        v-for="(tab, index) in tabs" 
        :key="index"
        class="tab" 
        :class="{ active: activeTab === index }"
        @tap="changeTab(index)"
      >
        {{ tab }}
      </text>
    </view>

    <!-- 订单列表 -->
    <view class="order-list">
      <view v-if="!orders.length" class="empty">
        <text class="empty-icon">📭</text>
        <text class="empty-text">暂无订单</text>
      </view>
      <view v-else class="order-item" v-for="order in orders" :key="order.id">
        <!-- 订单头部 -->
        <view class="order-header">
          <view class="user-info">
            <image class="avatar" :src="order.avatar || '/static/project/2025-10-14_110352_756.png'" mode="aspectFill" />
            <view class="user-detail">
              <text class="user-name">{{ order.userName }}</text>
              <text class="user-rating">口碑 {{ order.rating }}分</text>
            </view>
          </view>
          <text class="order-status" :class="order.statusClass">{{ order.statusText }}</text>
        </view>

        <!-- 订单详情 -->
        <view class="order-detail">
          <view class="detail-row" v-if="order.userPhone">
            <text class="icon">📞</text>
            <text class="text">{{ order.userPhone }}</text>
          </view>
          <view class="detail-row">
            <text class="icon">⏰</text>
            <text class="text">{{ order.time }}</text>
          </view>
          <view class="detail-row">
            <text class="icon">📍</text>
            <text class="text">{{ order.location }}</text>
          </view>
          <view class="detail-row">
            <text class="icon">👥</text>
            <text class="text">距离{{ order.distance }}</text>
          </view>
          <view class="detail-row" v-if="order.duration">
            <text class="icon">⏱️</text>
            <text class="text">预计时长：{{ order.duration }}</text>
          </view>
        </view>

        <!-- 订单底部 -->
        <view class="order-footer">
          <view class="price-info">
            <text class="label">{{ order.priceLabel || '配送' }}</text>
            <text class="price">¥{{ order.price }}</text>
          </view>
          <view class="actions">
            <button 
              v-if="order.showIgnore" 
              class="btn btn-ignore" 
              size="mini" 
              @tap="ignoreOrder(order)"
            >
              忽略
            </button>
            <button 
              v-if="order.showAccept" 
              class="btn btn-accept" 
              size="mini" 
              @tap="acceptOrder(order)"
            >
              接单
            </button>
            <button 
              v-if="order.showStart" 
              class="btn btn-start" 
              size="mini" 
              @tap="startOrder(order)"
            >
              开始服务
            </button>
            <button 
              v-if="order.showServiceDetail" 
              class="btn btn-service" 
              size="mini" 
              @tap="goToServiceDetail(order)"
            >
              服务详情
            </button>
            <button 
              v-if="order.showCancel" 
              class="btn btn-cancel" 
              size="mini" 
              @tap="cancelOrder(order)"
            >
              取消
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部占位 -->
    <view class="tabbar-placeholder"></view>
    
    <!-- Tabbar -->
    <climber-tabbar :active="1" />
  </view>
</template>

<script>
import ClimberTabbar from '@/components/climber-tabbar/climber-tabbar.vue'
import { getClimberOrders, cancelOrder as cancelOrderApi, startOrder as startOrderApi } from '@/api/order'

export default {
  components: { ClimberTabbar },
  data() {
    return {
      tabs: ['全部', '可接'],
      activeTab: 0,
      orders: [] // 从接口获取订单数据
    }
  },
  onLoad() {
    this.loadOrders()
  },
  methods: {
    changeTab(index) {
      this.activeTab = index
      this.loadOrders()
    },
    async loadOrders() {
      try {
        this.$modal.loading('加载中...')
        const response = await getClimberOrders()
        this.$modal.closeLoading()
        
        if (response.code === 200 && response.data) {
          // 将后端返回的订单数据转换为页面需要的格式
          this.orders = response.data.map(order => this.convertOrderFormat(order))
        } else {
          this.orders = []
        }
      } catch (error) {
        this.$modal.closeLoading()
        console.error('加载订单失败:', error)
        this.$modal.showToast('加载订单失败')
        this.orders = []
      }
    },
    
    // 转换订单数据格式
    convertOrderFormat(order) {
      // 格式化时间
      const formatTime = (date, start, end) => {
        if (!date || !start || !end) return '时间待定'
        const dateStr = date.replace(/-/g, '/')
        return `${dateStr} ${start}-${end}`
      }
      
      // 计算时长
      const calculateDuration = (start, end) => {
        if (!start || !end) return ''
        const [startH, startM] = start.split(':').map(Number)
        const [endH, endM] = end.split(':').map(Number)
        const minutes = (endH * 60 + endM) - (startH * 60 + startM)
        const hours = Math.floor(minutes / 60)
        const mins = minutes % 60
        if (hours > 0 && mins > 0) {
          return `${hours}小时${mins}分钟`
        } else if (hours > 0) {
          return `${hours}小时`
        } else {
          return `${mins}分钟`
        }
      }
      
      // 根据订单状态设置显示内容
      const getStatusInfo = (status, paymentStatus) => {
        switch(status) {
          case 'CONFIRMED':
            // 已接单，如果已支付则显示"开始服务"按钮
            const isPaid = paymentStatus === 'PAID'
            return { 
              text: isPaid ? '已支付' : '已接', 
              class: 'status-accepted', 
              showCancel: !isPaid,
              showStart: isPaid,
              showServiceDetail: false
            }
          case 'IN_PROGRESS':
            // 进行中，显示"服务详情"按钮
            return { 
              text: '进行中', 
              class: 'status-ongoing', 
              showCancel: false, 
              showStart: false,
              showServiceDetail: true
            }
          case 'COMPLETED':
            // 已完成，也可以查看服务记录
            return { 
              text: '已完成', 
              class: 'status-renewed', 
              showCancel: false, 
              showStart: false,
              showServiceDetail: true
            }
          case 'CANCELLED':
            return { 
              text: '已取消', 
              class: 'status-cancelled', 
              showCancel: false, 
              showStart: false,
              showServiceDetail: false
            }
          default:
            return { 
              text: '未知', 
              class: '', 
              showCancel: false, 
              showStart: false,
              showServiceDetail: false
            }
        }
      }
      
      const statusInfo = getStatusInfo(order.orderStatus, order.paymentStatus)
      
      return {
        id: order.id,
        userName: order.userName || '用户',
        userPhone: order.userPhone || '',
        avatar: '',
        rating: 4.8,
        statusText: statusInfo.text,
        statusClass: statusInfo.class,
        time: formatTime(order.serviceDate, order.startTime, order.endTime),
        location: order.routePlan || '黄山风景区',
        distance: `${order.participantCount || 1}人`,
        duration: calculateDuration(order.startTime, order.endTime),
        priceLabel: '',
        price: order.amount || 0,
        showIgnore: false,
        showAccept: false,
        showStart: statusInfo.showStart,
        showCancel: statusInfo.showCancel,
        showServiceDetail: statusInfo.showServiceDetail
      }
    },
    
    ignoreOrder(order) {
      this.$modal.showToast('已忽略订单')
      this.orders = this.orders.filter(o => o.id !== order.id)
    },
    
    acceptOrder(order) {
      uni.showModal({
        title: '确认接单',
        content: `确定接受${order.userName}的订单吗？`,
        success: (res) => {
          if (res.confirm) {
            this.$modal.showToast('接单成功')
            this.loadOrders()
          }
        }
      })
    },
    
    async cancelOrder(order) {
      uni.showModal({
        title: '取消订单',
        content: '确定要取消该订单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              this.$modal.loading('取消中...')
              const response = await cancelOrderApi(order.id, '配爬员取消订单')
              this.$modal.closeLoading()
              
              if (response.code === 200) {
                this.$modal.showToast('已取消订单')
                await this.loadOrders()
              } else {
                this.$modal.showToast(response.msg || '取消失败')
              }
            } catch (error) {
              this.$modal.closeLoading()
              console.error('取消订单失败:', error)
              this.$modal.showToast('取消订单失败，请重试')
            }
          }
        }
      })
    },
    
    async startOrder(order) {
      uni.showModal({
        title: '开始服务',
        content: '确定要开始为用户提供服务吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              this.$modal.loading('处理中...')
              const response = await startOrderApi(order.id)
              this.$modal.closeLoading()
              
              if (response.code === 200) {
                this.$modal.showToast('服务已开始')
                await this.loadOrders()
              } else {
                this.$modal.showToast(response.msg || '操作失败')
              }
            } catch (error) {
              this.$modal.closeLoading()
              console.error('开始服务失败:', error)
              this.$modal.showToast('操作失败，请重试')
            }
          }
        }
      })
    },
    
    // 跳转到服务详情页
    goToServiceDetail(order) {
      uni.navigateTo({
        url: `/pages/climber/service-detail?id=${order.id}`
      })
    }
  }
}
</script>

<style scoped>
.climber-orders {
  min-height: 100vh;
  background: #f5f6f7;
}

/* 头部 */
.header {
  background: #fff;
  padding: 32rpx;
  text-align: center;
}

.title {
  font-size: 36rpx;
  font-weight: 700;
  color: #333;
}

/* 筛选标签 */
.filter-tabs {
  background: #fff;
  display: flex;
  padding: 0 32rpx 20rpx;
  gap: 20rpx;
}

.tab {
  font-size: 28rpx;
  color: #666;
  padding: 8rpx 24rpx;
  border-radius: 20rpx;
  background: #f5f6f7;
}

.tab.active {
  background: #1989fa;
  color: #fff;
  font-weight: 600;
}

/* 订单列表 */
.order-list {
  padding: 20rpx 32rpx;
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-icon {
  font-size: 100rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.order-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 16rpx;
}

.user-detail {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 8rpx;
}

.user-rating {
  font-size: 24rpx;
  color: #999;
}

.order-status {
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  color: #fff;
}

.status-ongoing {
  background: #ff9500;
}

.status-accepted {
  background: #07c160;
}

.status-renewed {
  background: #1989fa;
}

.status-cancelled {
  background: #999;
}

/* 订单详情 */
.order-detail {
  margin-bottom: 20rpx;
}

.detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.detail-row .icon {
  font-size: 28rpx;
  margin-right: 8rpx;
}

.detail-row .text {
  font-size: 26rpx;
  color: #666;
}

/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1rpx solid #f0f0f0;
  padding-top: 20rpx;
}

.price-info {
  display: flex;
  align-items: baseline;
}

.label {
  font-size: 22rpx;
  color: #ff9500;
  background: #fff3e0;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  margin-right: 12rpx;
}

.price {
  font-size: 36rpx;
  font-weight: 700;
  color: #ff6b00;
}

.actions {
  display: flex;
  gap: 16rpx;
}

.btn {
  border: none;
  padding: 10rpx 24rpx;
  border-radius: 8rpx;
  font-size: 26rpx;
}

.btn-ignore {
  background: #f5f6f7;
  color: #666;
}

.btn-accept {
  background: #1989fa;
  color: #fff;
}

.btn-start {
  background: #07c160;
  color: #fff;
}

.btn-cancel {
  background: #fff;
  color: #666;
  border: 1rpx solid #ddd;
}

.btn-service {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

/* 底部占位 */
.tabbar-placeholder {
  height: 120rpx;
}
</style>

